/**
 * +----------------------------------------------------------------------------------------------+
 * |Date               |  Version  |Author             |Description                              |
 * |==========+=======+==============+===================|
 * |2017年10月8日     |  1.0.0       | kreo                 |Initial                                       |
 * +----------------------------------------------------------------------------------------------+
 */
package main.java.utils.hxy.thread.thread;

import com.wanma.framework.util.IKit;

import java.util.concurrent.Callable;

/**
 * 多线程跑任务时 , 加入登录信息 (由于用户信息在系统中是 ThreadLocal的 , 所以在非业务中 , 无法通过IKit获取到用户信息)
 *
 * @ClassName ContextRunnable
 * @Description
 */
public class IContextRunnable {

    public static Runnable runnable(Runnable execute) {
        final String isessionid = IKit.getISessionId();
        return () -> {
            try {
                IKit.putISessionId(isessionid);
                execute.run();
            } finally {
                IKit.removeISessionId();
            }
        };
    }

    public static <T> Callable<T> callable(Callable<T> execute) {
        final String isessionid = IKit.getISessionId();
        return () -> {
            try {
                IKit.putISessionId(isessionid);
                return execute.call();
            } finally {
                IKit.removeISessionId();
            }
        };
    }

    public static void main(String[] args) {

        IThreadPool.addTask(IContextRunnable.runnable(() -> {
        }));

        IThreadPool.addCallable(IContextRunnable.callable(() -> ""));
    }
}
